<?php
namespace Wechat\Controller;

use App\Controller\AppController as BaseController;
use Cake\Event\Event;

/**
 * 微信总控制器
 *
 * @property \Wechat\Controller\Component\WechatComponent $Wechat
 */
class AppController extends BaseController
{

    var $aId = 10000;

    var $fuid = 0;

    var $openid = "";

    var $return_url = "redirect";

    var $allowedActions = [];

    var $wxLoginActions = [];

    public function beforeFilter(Event $event)
    {
        header ( 'Access-Control-Allow-Origin:*' );
        header ( "Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept" );
        header ( "Access-Control-Allow-Methods: GET,POST,PUT" );
        header ( "Access-Control-Max-Age: 1728000" );
        parent::beforeFilter($event);
        $this->aId = $this->request->getQuery("app", 10000);
        // 需要判断是否登录了微信
        $wxcookieMember = $this->Cookie->read($this->wxloginCookiesKey);
        $action = $this->request->getParam('action');
        $this->request->addDetector ( 'wechat', [
            'env' => 'HTTP_USER_AGENT',
            'pattern' => '/MicroMessenger/i'
        ] );
        if (! empty($wxcookieMember)) {
            if(!empty($wxcookieMember["aid"])){
                $this->aId = $wxcookieMember["aid"];
            }
            $this->openid = $wxcookieMember["openid"];
            if(empty($wxcookieMember["id"])){
                $cookie = $this->Cookie->read($this->loginCookiesKey);
                if(!empty($cookie)){
                    $this->uid=$cookie["id"];
                }
            }else{
                $this->uid = $wxcookieMember["id"];
            }
            // 已经微信登录,需要检查过期时间
            /* if (! $this->checkAccessToken($wxcookieMember)) {
            } else {
                // 需要重新授权
                $this->reAuth();
            } */
        } elseif (in_array($action, $this->wxLoginActions) && $this->request->is("wechat")&& !$this->request->is("json")) {
            // 拦截强制跳转到登录授权
            $this->reAuth();
        }
    }

    /**
     * 拦截强制跳转到登录授权
     */
    private function reAuth()
    {
        $logAction = [
            'action' => 'index',
            'controller' => 'Login',
            '_ext' => 'html',
            'plugin' => 'Wechat',
            'app' => $this->aId
        ];
        $this->Auth->setConfig("loginAction", $logAction);
        $this->Auth->deny();
    }

    /**
     * 检查token是否过期
     */
    public function checkAccessToken($cookieMember)
    {
        $n = time();
        $m = $cookieMember["t"];
        $expires_in = 7200;
        // 还有10分钟到期，则自动续期
        if (($n - $m + 1200) > $expires_in) {
            $this->loadComponent('Wechat.Wechat', [
                'id' => $this->appId
            ]);
            $data = $this->Wechat->findWxUserByOpenid($cookieMember["openid"]);
            // 刷新token
            $result = $this->Wechat->getWxRefreshToken($data);
            if (! $result) {
                $this->log("令牌过期，重新授权" . $cookieMember["openid"]);
                $this->Cookie->configKey($this->return_url, 'expires', '+30 minutes');
                $this->Cookie->write($this->return_url, $this->getFullUrl());
                $this->Cookie->delete($this->wxloginCookiesKey);
                return true;
            }
            // 只需要更新cookie中的t，改成当前时间，表示每次授权登陆起，开始计算
            $cookieMember["t"] = time();
            $this->Cookie->write($this->wxloginCookiesKey, $cookieMember);
        }
        return false;
    }

    public function getAreaByIp($ip)
    {
        $this->loadComponent("Utils.Ip");
        return $this->Ip->getIp($ip);
    }
}
